#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
定时任务调度器
每天早8点自动发送新闻日报
"""

import schedule
import time
import logging
from datetime import datetime
from news_daily import NewsDailyGenerator
import signal
import sys
import os


class NewsDailyScheduler:
    """新闻日报定时调度器"""
    
    def __init__(self, 
                 sender_email: str,
                 sender_password: str,
                 recipient_email: str = "505735255@qq.com",
                 rss_url: str = "https://rss.aishort.top/?type=36kr",
                 send_time: str = "08:00"):
        """
        初始化调度器
        
        Args:
            sender_email: 发送邮箱
            sender_password: 发送邮箱密码/授权码
            recipient_email: 接收邮箱
            rss_url: RSS新闻源地址
            send_time: 发送时间 (HH:MM格式)
        """
        self.sender_email = sender_email
        self.sender_password = sender_password
        self.recipient_email = recipient_email
        self.rss_url = rss_url
        self.send_time = send_time
        
        # 创建新闻日报生成器
        self.generator = NewsDailyGenerator(
            rss_url=rss_url,
            sender_email=sender_email,
            sender_password=sender_password,
            recipient_email=recipient_email
        )
        
        # 设置日志
        self._setup_logging()
        
        # 设置信号处理
        self._setup_signal_handlers()
        
        self.running = False
    
    def _setup_logging(self):
        """设置日志记录"""
        log_dir = "logs"
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        
        log_file = os.path.join(log_dir, f"scheduler_{datetime.now().strftime('%Y%m%d')}.log")
        
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)
    
    def _setup_signal_handlers(self):
        """设置信号处理器"""
        def signal_handler(signum, frame):
            self.logger.info(f"接收到信号 {signum}，正在停止调度器...")
            self.stop()
            sys.exit(0)
        
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
    
    def send_daily_news(self):
        """发送每日新闻（定时任务函数）"""
        self.logger.info("开始执行定时新闻发送任务...")
        
        try:
            # 生成并发送日报
            success = self.generator.generate_and_send_daily(max_news_items=8)
            
            if success:
                self.logger.info("✅ 每日新闻发送成功")
            else:
                self.logger.error("❌ 每日新闻发送失败")
                
        except Exception as e:
            self.logger.error(f"发送每日新闻时发生错误: {e}")
    
    def setup_schedule(self):
        """设置定时任务"""
        self.logger.info(f"设置定时任务: 每天 {self.send_time} 发送新闻日报")
        
        # 设置每天定时发送
        schedule.every().day.at(self.send_time).do(self.send_daily_news)
        
        # 可选：设置测试任务（每分钟执行一次，用于测试）
        # schedule.every().minute.do(self.send_daily_news)
        
        self.logger.info("定时任务设置完成")
    
    def run(self):
        """运行调度器"""
        self.logger.info("启动新闻日报调度器...")
        self.logger.info(f"发送邮箱: {self.sender_email}")
        self.logger.info(f"接收邮箱: {self.recipient_email}")
        self.logger.info(f"RSS源: {self.rss_url}")
        self.logger.info(f"发送时间: 每天 {self.send_time}")
        
        # 设置定时任务
        self.setup_schedule()
        
        # 显示下次执行时间
        next_run = schedule.next_run()
        if next_run:
            self.logger.info(f"下次执行时间: {next_run}")
        
        self.running = True
        
        try:
            while self.running:
                schedule.run_pending()
                time.sleep(60)  # 每分钟检查一次
                
        except KeyboardInterrupt:
            self.logger.info("接收到中断信号，正在停止...")
        except Exception as e:
            self.logger.error(f"调度器运行时发生错误: {e}")
        finally:
            self.stop()
    
    def stop(self):
        """停止调度器"""
        self.logger.info("正在停止调度器...")
        self.running = False
        schedule.clear()
        self.logger.info("调度器已停止")
    
    def test_send(self):
        """测试发送（立即发送一次）"""
        self.logger.info("执行测试发送...")
        self.send_daily_news()
    
    def show_status(self):
        """显示调度器状态"""
        print("=== 新闻日报调度器状态 ===")
        print(f"发送邮箱: {self.sender_email}")
        print(f"接收邮箱: {self.recipient_email}")
        print(f"RSS源: {self.rss_url}")
        print(f"发送时间: 每天 {self.send_time}")
        print(f"运行状态: {'运行中' if self.running else '已停止'}")
        
        next_run = schedule.next_run()
        if next_run:
            print(f"下次执行: {next_run}")
        else:
            print("下次执行: 无计划任务")


def create_scheduler_from_config(config_file: str = "email_config.py") -> NewsDailyScheduler:
    """
    从配置文件创建调度器
    
    Args:
        config_file: 配置文件路径
        
    Returns:
        NewsDailyScheduler实例
    """
    try:
        # 动态导入配置文件
        import importlib.util
        spec = importlib.util.spec_from_file_location("email_config", config_file)
        config = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(config)
        
        return NewsDailyScheduler(
            sender_email=config.SENDER_EMAIL,
            sender_password=config.SENDER_PASSWORD,
            recipient_email=config.RECIPIENT_EMAIL,
            rss_url=config.RSS_URL,
            send_time=config.SEND_TIME
        )
        
    except Exception as e:
        print(f"从配置文件创建调度器失败: {e}")
        return None


def main():
    """主函数"""
    print("=== 新闻日报定时调度器 ===")
    print("1. 从配置文件启动")
    print("2. 手动配置启动")
    print("3. 测试发送")
    print("4. 显示状态")
    
    choice = input("请选择 (1-4): ").strip()
    
    if choice == "1":
        # 从配置文件启动
        scheduler = create_scheduler_from_config()
        if scheduler:
            scheduler.run()
        else:
            print("❌ 无法从配置文件创建调度器")
    
    elif choice == "2":
        # 手动配置启动
        sender_email = input("发送邮箱: ").strip()
        sender_password = input("发送邮箱授权码: ").strip()
        recipient_email = input("接收邮箱 (默认: 505735255@qq.com): ").strip() or "505735255@qq.com"
        send_time = input("发送时间 (默认: 08:00): ").strip() or "08:00"
        
        scheduler = NewsDailyScheduler(
            sender_email=sender_email,
            sender_password=sender_password,
            recipient_email=recipient_email,
            send_time=send_time
        )
        
        scheduler.run()
    
    elif choice == "3":
        # 测试发送
        sender_email = input("发送邮箱: ").strip()
        sender_password = input("发送邮箱授权码: ").strip()
        recipient_email = input("接收邮箱 (默认: 505735255@qq.com): ").strip() or "505735255@qq.com"
        
        scheduler = NewsDailyScheduler(
            sender_email=sender_email,
            sender_password=sender_password,
            recipient_email=recipient_email
        )
        
        scheduler.test_send()
    
    elif choice == "4":
        # 显示状态
        scheduler = create_scheduler_from_config()
        if scheduler:
            scheduler.show_status()
        else:
            print("❌ 无法加载配置文件")
    
    else:
        print("无效选择")


if __name__ == "__main__":
    main()
